# -*- coding: utf-8 -*-
import http.client
import json
from comm.module import *
from comm.LogUtils import logger
from comm.postgresutility import postsql_utility

# 获取场所类型列表
def doGettypeList():
   try:
      logger.info('101:获取场所类型列表')
      conn = http.client.HTTPSConnection(global_url)
      payload = ''
      headers = {
         'app-id': global_appid,
         'app-key': global_appkey
      }
      conn.request("GET", "/openapi/locale/typeList", payload, headers)
      res = conn.getresponse()
      data = res.read()
      # print(data.decode("utf-8"))
      logger.info('101:' + data.decode("utf-8"))
      conn.close()
   except Exception as e:
      logger.info('101:错误'+str(e))

# 场所列表树　获取场所id
def doGetlocalelist():
    try:
        logger.info('103:场所列表树')
        conn = http.client.HTTPSConnection(global_url)
        payload = ''
        headers = {
            'app-id': global_appid,
            'app-key': global_appkey
        }
        conn.request("GET", "/openapi/locale/list", payload, headers)
        res = conn.getresponse()
        data = res.read()
        print(data.decode("utf-8"))
        conn.close()

        # 遍历数据
        json_str = json.loads(data)
        ierrCode = json_str["errCode"]
        if (ierrCode == 200):
            isite_id = json_str["data"][0]["id"]
            isite_name = json_str["data"][0]["name"]
            sql = "update a_ts_site set fboxflag=" + str(isite_id)
            sql = sql + ",fsite_name='" + isite_name + "'"
            sql = sql + " where fsite_no='" + global_site + "'"
            conn, cursor = postsql_utility.get_conn()
            i = postsql_utility.execute(sql=sql, cursor=cursor, connect=conn)
            if i != "OK":
                print("失败" + str(i))
            else:
                print("成功" + str(i))
        else:
            print(json_str["errMsg"])

    except Exception as e:
        logger.info('103:错误'+str(e))

# 新增或编辑场所
# 0:区域,1:楼,2:房间,3:教室,4:实验室
def doAddlocale():
   try:
      logger.info('102:新增或编辑场所');
      # 上传格式
      # payload = json.dumps({
      #    "adminUserIds": [
      #       160,
      #       164
      #    ],
      #    "type": 0,
      #    "name": "医学院东校区",
      #    "address": "宁夏回族自治区赤峰市太白县"
      # })

      #  客户资料
      #  先执行新增操作
      sql = "select fsite_no ,fsite_name ,0 ftype,'' address,fboxflag id "
      sql = sql +" from a_ts_site"
      sql = sql +" where 1=1"
      sql = sql +" and fsite_no='"+global_site+"'"
      sql = sql +" and ((fboxflag is null) or (fboxflag=0))"
      sql = sql +" order by fsite_no;"
      logger.info('102:' + sql)
      conn, cursor = postsql_utility.get_conn()
      data = postsql_utility.select(sql=sql, cursor=cursor)

      data_list=[]
      for j1 in range(len(data)):
          data_dict = {}
          #data_dict["id"] = 381
          data_dict["name"] = data[j1][1]
          doors_list = []
          data_dict["adminUserIds"] = doors_list
          data_dict["type"] = data[j1][2]
          data_dict["address"] = data[j1][3]
          #print(data_dict)
          data_list.append(data_dict)
          #调用接口
          py_dict = str(data_list[0])
          doAddlocale2(1,0,data[j1][0],py_dict)

      # 楼
      sql = "select fpoint_no ,fpoint_name ,'' address"
      sql = sql +",case fpoint_flag when 2 then 1 else 4 end ftype"
      sql = sql +",b.fboxflag fparent_no "
      sql = sql + " from a_ts_point a,a_ts_site b"
      sql = sql + " where 1=1"
      sql = sql + " and a.fsite_no='" + global_site + "'"
      sql = sql + " and a.fpoint_flag =2 "
      sql = sql + " and ((fmjtype is null) or (fmjtype=0))"
      sql = sql + " and a.fsite_no=b.fsite_no"
      sql = sql + " order by a.fpoint_no;"
      logger.info('102:' + sql)
      data = postsql_utility.select(sql=sql, cursor=cursor)

      data_list = []
      for j1 in range(len(data)):
          data_dict = {}
          #data_dict["id"] = int(data[j1][0])
          data_dict["name"] = data[j1][1]
          doors_list = []
          data_dict["adminUserIds"] = doors_list
          data_dict["type"] = data[j1][3]
          data_dict["address"] = data[j1][2]
          data_dict["parentId"] = data[j1][4]
          #print(data_dict)
          data_list.append(data_dict)
          # 调用接口
          py_dict = str(data_list[j1])
          doAddlocale2(1, 1, data[j1][0], py_dict)

      # 实验室
      sql = "select fpoint_no ,fpoint_name ,'' address"
      sql = sql + ",case fpoint_flag when 2 then 1 else 4 end ftype"
      sql = sql + ",b.fboxflag fparent_no "
      sql = sql + " from a_ts_point a,a_ts_site b"
      sql = sql + " where 1=1"
      sql = sql + " and a.fsite_no='" + global_site + "'"
      sql = sql + " and a.fpoint_flag =0 "
      sql = sql + " and ((fmjtype is null) or (fmjtype=0))"
      sql = sql + " and a.fsite_no=b.fsite_no"
      sql = sql + " order by a.fpoint_no;"
      logger.info('102:' + sql)
      data = postsql_utility.select(sql=sql, cursor=cursor)

      data_list = []
      for j1 in range(len(data)):
          data_dict = {}
          # data_dict["id"] = int(data[j1][0])
          data_dict["name"] = data[j1][1]
          doors_list = []
          data_dict["adminUserIds"] = doors_list
          data_dict["type"] = data[j1][3]
          data_dict["address"] = data[j1][2]
          data_dict["parentId"] = data[j1][4]
          # print(data_dict)
          data_list.append(data_dict)
          # 调用接口
          py_dict = str(data_list[j1])
          doAddlocale2(1, 1, data[j1][0], py_dict)

   except Exception as e:
      logger.info('102:错误'+str(e))

# 新增或编辑场所
def doAddlocale2(py_flag,py_level,py_name,py_dict):
   try:
      logger.info('103:' + py_dict)
      conn = http.client.HTTPSConnection(global_url)
      #payload = json.dumps(py_dict,ensure_ascii=False) #.decode('utf-8').encode('gb2312')
      payload = py_dict.encode('utf-8').decode('latin-1')
      #print(payload)
      # payload = json.dumps({
      #     "adminUserIds": [
      #         160,
      #         164
      #     ],
      #     "id": 380,
      #     "type": 0,
      #     "name": "医学院东校区",
      #     "address": "宁夏回族自治区赤峰市太白县"
      # })
      headers = {
         'app-id': global_appid,
         'app-key': global_appkey,
         'Content-Type': 'application/json'
      }
      conn.request("POST", "/openapi/locale/added", payload, headers)
      res = conn.getresponse()
      data = res.read()
      data = data.decode("utf-8")
      #print(data.decode("utf-8"))
      #{"data":{"address":"宁夏回族自治区赤峰市太白县","adminUserIds":[160,164],"companyId":24,"id":380,"name":"医学院东校区","type":0},"errCode":200,"success":true}
      logger.info('103:' + data)
      conn.close()

      if (py_flag==2):
          print("修改")
      else:
          # 新增 依据返回值刷新id
          json_str = json.loads(data)
          ierrCode = json_str["errCode"]
          if (ierrCode == 200):
              data_json = json_str["data"]
              id = data_json["id"]
              #print(id, end="\n")
              sql=""
              if (py_level==0):
                  sql="update a_ts_site  set fappurl=to_char(NOW(), 'YYYY-MM-DD HH24:MI:SS')"
                  sql= sql +",fboxflag="+str(id)
                  sql= sql +" where fsite_no='" + global_site + "';"
              else:
                  sql = "update a_ts_point  set fappno=to_char(NOW(), 'YYYY-MM-DD HH24:MI:SS')"
                  sql = sql + ",fmjtype=" + str(id)
                  sql = sql + " where fpoint_no='"+py_name+"'"
                  sql = sql + " and fsite_no='" + global_site + "';"
              #print(sql)
              conn, cursor = postsql_utility.get_conn()
              i = postsql_utility.execute(sql=sql, cursor=cursor, connect=conn)
              if i != "OK":
                  print(py_name+"->失败" + str(i))
              else:
                  print(py_name+"->成功" + str(i))


   except Exception as e:
      logger.info('103:错误'+str(e))

#直接调试
#doGetlocalelist()

#doAddlocale()
